package com.wzy.business.store.main.fragment

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.wangzhenyu.common.base.IConstant
import com.wangzhenyu.common.base.bean.LoginInfo
import com.wangzhenyu.common.base.bean.UserManager
import com.wangzhenyu.common.base.delegate.BaseVBPFragment
import com.wangzhenyu.common.util.exts.gone
import com.wangzhenyu.common.util.exts.inVisible
import com.wangzhenyu.common.util.exts.visible
import com.wzy.business.R
import com.wzy.business.base.ShopStatusConstants
import com.wzy.business.databinding.FragmentNewMainBinding
import com.wzy.business.store.main.ApplyShopHintActivity
import com.wzy.business.store.main.MainActivity
import com.wzy.business.store.main.MainViewModel
import com.wzy.business.store.main.bean.MainInfo
import com.wzy.business.store.main.bean.MainInfoVo
import com.wzy.business.store.main.bean.ShopStatus
import com.wzy.business.store.main.pop.ApplyInfoPop
import com.wzy.business.store.main.presenter.MainPresenter
import com.wzy.business.store.main.presenter.impl.MainPresenterImpl
import com.wzy.business.store.me.bean.AccountSetting
import com.wzy.business.util.GlideUtils
import com.wzy.business.util.OtherUtils


class NewMainFragment : BaseVBPFragment<FragmentNewMainBinding, MainPresenter>(),
    MainPresenter.View {


    override fun getBinding(inflater: LayoutInflater, container: ViewGroup?) =
        FragmentNewMainBinding.inflate(inflater, container, false)


    override fun createPresenter() = MainPresenterImpl(requireContext(), this)

    //店铺状态及信息
    private var shopStatus: ShopStatus? = null

    private val model by activityViewModels<MainViewModel>()

    // 首页订单统计数据
    private var mainInfo: MainInfoVo? = null
    private var loginInfo: LoginInfo? = null
    private var fromMain: Boolean? = null
    private var versionUpdateDialog: AppCompatDialog? = null
    private var accountSetting: AccountSetting? = null

    //信息选择
    //弹出的东西
    private var pop: ApplyInfoPop? = null

    //今日开始时间
    var startTime: Long? = null

    //今日结束时间
    var endTime: Long? = null

    override fun initViewsAndData(rootView: View) {


        showPageLoading()

        //
        mPresenter?.requestMainInfoData()

        mPresenter?.requestAccountSettingData()


        mbinding.apply {
            tvMainShopNext.setOnClickListener {
                when (tvMainShopNext.text.toString()) {
                    "申请开店 >>", "重新提交" -> {
                        ActivityUtils.startActivity(ApplyShopHintActivity::class.java)
                    }

                    "联系客服" -> {
                        OtherUtils.goToDialApp(activity, IConstant.SERVICE_PHONE)
                    }

                    "立即购买" -> {
                        //ActivityUtils.startActivity(ApplyVipActivity::class.java)
                    }
                }
            }


            // pop?.liveData?.observe(this, Observer {
            //            if (it == 0) {
            //                //补充进件资料
            //                WebCameraUtil.permissionHandle(activity, callBack)
            //            } else {
            //                //重新提交店铺资料
            //                ApplyShopInfoActivity.openActivity(requireContext(), false)
            //            }
            //
            //            pop?.dismiss()
            //        })

        }
    }

    override fun onMainInfoSuccess(bean: MainInfo?) {

    }

    override fun onMainDataSuccess(bean: MainInfoVo?, status: ShopStatus?) {

        startTime = bean?.start_time
        endTime = bean?.end_time

        hidePageLoading()
        shopStatus = status
        mainInfo = bean
        mbinding.smartRefreshLayout.isRefreshing = false
        initShopStatus(UserManager.getLoginInfo())
    }

    override fun onMainInfoError(code: Int) {
        mbinding.smartRefreshLayout.isRefreshing = false
        hidePageLoading()
    }


    //初始化店铺状态
    private fun initShopStatus(loginInfo: LoginInfo?) {
        this.loginInfo = loginInfo

        mbinding.apply {

            llMainShopOpen.visibility = View.GONE
            llMainShopOther.visibility = View.VISIBLE
            tvMainShopReason.visibility = View.GONE
            llHeader.visibility = View.GONE
            ivMainMessage.visibility = View.GONE

            if (loginInfo != null) {
                //            APPLY("申请开店")	等待审核结果	等待审核提示页面---联系客服
                //            APPLYING("申请中")	申请信息的填写过程中	申请信息填写页面 ---重新填写
                //            OPEN("开启中")	正常	首页
                //            CLOSED("店铺关闭")	禁止运营	店铺关闭提示页面---联系客服
                //            REFUSED("审核拒绝")	修改注册重新申请	审核拒绝提示页面---重新填写
                //            UN_APPLY("未开店")	申请开店	申请开店提示页面 ---联系客服
                when (loginInfo.shopStatus) {
                    ShopStatusConstants.UN_APPLY -> {
                        tvMainShopHint.text = "你还有没有开通店铺"
                        tvMainShopNext.text = "申请开店 >>"
                        remark.gone()
                    }

                    ShopStatusConstants.APPLY,
                    ShopStatusConstants.APPLYING -> {
                        tvMainShopName.text = "店铺待审核"
                        tvMainShopNext.text = "联系客服"
                        SpanUtils.with(tvMainShopHint)
                            .append("申请正在").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_909090
                                )
                            )
                            .append("审核中").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_fc0000
                                )
                            )
                            .append("，请耐心等待..").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_909090
                                )
                            )
                            .create()
                        remark.gone()
                    }

                    ShopStatusConstants.OPEN,
                    ShopStatusConstants.OVERDUE,
                    ShopStatusConstants.ALLINPAY_APPLYING,
                    ShopStatusConstants.ALLINPAY_APPROVED,
                    ShopStatusConstants.ALLINPAY_COMPLIANCE_REFUSED,
                    ShopStatusConstants.ALLINPAY_ELECTSIGN_REFUSED,
                    ShopStatusConstants.ALLINPAY_ELECTSIGN_APPROVED,
                    ShopStatusConstants.ALLINPAY_ELECTSIGN_ING,
                    ShopStatusConstants.WEIXIN_AUTHEN_APPLYING,
                    ShopStatusConstants.FINAL_OPEN -> {
                        if (fromMain != true && ActivityUtils.getTopActivity() !is MainActivity) {
                            versionUpdateDialog?.dismiss()
                            activity?.finish()
                            ActivityUtils.startActivity(MainActivity::class.java)
                            return
                        }
                        llHeader.visibility = View.VISIBLE
                        llHeader.setBackgroundColor(
                            ContextCompat.getColor(
                                requireContext(),
                                R.color.primary
                            )
                        )
                        llMainShopOpen.visibility = View.VISIBLE
                        llMainShopOther.visibility = View.GONE
                        ivMainMessage.visibility = View.VISIBLE

                        // 认证中
                        authLayout.gone()
                        shopAuthHint.gone()
                        shopStatusLayout.gone()

                        if (loginInfo.shopStatus == ShopStatusConstants.OPEN ||
                            loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_APPLYING
                        ) {
                            // 开启中，显示审核中
                            authLayout.inVisible()
                            shopAuthStatus.text = "店铺审核中"
                            shopAuthHint.gone()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_APPROVED) {
                            // 进见通过，显示电子签约
                            authLayout.inVisible()
                            shopAuthStatus.text = "审核通过,请进行电子签约"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_ING) {
                            // 签约审核中
                            authLayout.inVisible()
                            shopAuthStatus.text = "签约已提交，等待通过"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_COMPLIANCE_REFUSED) {
                            // 进见补充资料
                            authLayout.inVisible()
                            shopAuthStatus.text = "店铺信息审核异常，请及时处理"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_APPROVED) {
                            // 微信认证中
                            authLayout.inVisible()
                            shopAuthStatus.text = "店铺签约成功,请进行商户认证"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_APPROVED) {
                            // 微信认证中
                            authLayout.inVisible()
                            shopAuthStatus.text = "店铺签约成功,请进行商户认证"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.WEIXIN_AUTHEN_APPLYING) {
                            // 微信认证中
                            authLayout.inVisible()
                            shopAuthStatus.text = "店铺签约成功,请进行商户认证"
                            shopAuthHint.inVisible()
                            //DialogUtils.showImageDialog(activity!!, R.mipmap.wechat_account, "店铺签约成功，请使用微信扫码进行商户认证，认证成功后才进行正常结算");
                        } else if (loginInfo.shopStatus == ShopStatusConstants.OVERDUE) {
                            // 过期
                            authLayout.inVisible()
                            shopAuthStatus.text = "会员已过期,请继续购买"
                            shopAuthHint.inVisible()
                        } else if (loginInfo.shopStatus == ShopStatusConstants.FINAL_OPEN) {
                            // 最终状态，显示店铺状态
                            shopStatusLayout.inVisible()
                            // mPresenter?.getWaringNumber()
                            switchStatusBtn.setCheckedNoEvent(loginInfo.openStatus ?: false)
                        }
                        //                    tvMainShopName.text=loginInfo?.nickname
                        initOpeningShopView()
                        remark.gone()
                    }

                    ShopStatusConstants.CLOSED -> {
                        tvMainShopName.text = "店铺已关闭"
                        tvMainShopNext.text = "联系客服"
                        SpanUtils.with(tvMainShopHint)
                            .append("您的店铺").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_909090
                                )
                            )
                            .append("已关闭").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_fc0000
                                )
                            )
                            .create()
                        remark.gone()
                    }

                    ShopStatusConstants.REFUSED,
                    ShopStatusConstants.ALLINPAY_REFUSED -> {
                        //店铺审核未通过，重新提交页面
                        tvMainShopName.text = "店铺审核未通过"
                        tvMainShopNext.text = "重新提交"

                        if (!shopStatus?.remark.isNullOrEmpty()) {
                            remark.visible()
                            remark.text = shopStatus?.remark
                        }
                        SpanUtils.with(tvMainShopHint)
                            .append("店铺申请资料").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_909090
                                )
                            )
                            .append("审核不通过\n").setForegroundColor(
                                ContextCompat.getColor(
                                    Utils.getApp(),
                                    R.color.color_fc0000
                                )
                            )
                            .create()
                    }
                }
            }
        }
    }

    private fun setShop() {
        val loginInfo = UserManager.getLoginInfo()
        loginInfo?.let {
            mbinding.tvMainShopName.text = loginInfo.shopName
            if (!TextUtils.isEmpty(loginInfo.shopLogo)) {
                GlideUtils.setImageUrl(mbinding.civMainShopHead, loginInfo.shopLogo)
            }
        }
    }

    private fun initOpeningShopView() {
        if (mainInfo == null) {
            return
        }

//        mbinding.apply {
//            setShop()
//
//            switchStatusBtn.setOnCheckedChangeListener { _, isChecked ->
//                mPresenter?.editShopStatus(if (isChecked) 1 else 0)
//            }
//            onShopStatusEdited()
//            // 申请状态点击
//            authLayout.setOnClickListener {
//                if (loginInfo?.shopStatus == ShopStatusConstants.ALLINPAY_COMPLIANCE_REFUSED) {
//                    // 进见补填
//                    pop?.apply {
//                        setList(
//                            listOf(
//                                "店铺信息不完善，点击前去补充资料",
//                                "店铺资料有变动，点击重新申请"
//                            )
//                        )
//                        setTitle("提示")
//                        showPopupWindow()
//                    }
//
//                } else if (loginInfo?.shopStatus == ShopStatusConstants.ALLINPAY_APPROVED
//                    || loginInfo?.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_ING
//                    || loginInfo?.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_REFUSED
//                ) {
//                    // 电子签约
//                    ActivityUtils.startActivity(ElectricSignActivity::class.java)
//                } else if (loginInfo?.shopStatus == ShopStatusConstants.ALLINPAY_ELECTSIGN_APPROVED
//                    || loginInfo?.shopStatus == ShopStatusConstants.WEIXIN_AUTHEN_APPLYING
//                ) {
//                    // 微信认证
//                    ActivityUtils.startActivity(ShopWeChatApproveActivity::class.java)
//                } else if (loginInfo?.shopStatus == ShopStatusConstants.OVERDUE) {
//                    // 过期续费
//                    ActivityUtils.startActivity(ApplyVipActivity::class.java)
//                }
//            }
//
//            // 总信息
//            // 未接订单
//            tvTodayUnTakeOrderCount.text = String.format("%s", mainInfo?.waitAcceptNum)
//            // 已接订单
//            tvTodayTakenOrderCount.text = String.format("%s", mainInfo?.alreadyAcceptNum)
//            // 待配送
//            tvTodayDistributeOrderCount.text = String.format("%s", mainInfo?.waitRogNum)
//
//            // 待退款
//            tvTodayRefund.text = String.format("%s", mainInfo?.refundNum)
//            // 已完成
//            tvTodayFinish.text = String.format("%s", mainInfo?.completeNum)
//            // 失效订单
//            tvTodayInvalid.text = String.format("%s", mainInfo?.cancelNum)
//
//            //销售额
//            tvTodaySales.text = String.format("%s", mainInfo?.tradeAmount)
//            // 新用户数
//            tvTodayNewUser.text = String.format("%s", mainInfo?.newMemberNum)
//            // 订单量
//            tvTodayOrderCount.text = String.format("%s", mainInfo?.allNum)
//
//            // 管理设置
//            tvManagerSetting.setOnClickListener {
//                ActivityUtils.startActivity(OperationSettingActivity::class.java)
//            }
//            // 商品管理
//            tvGoodsManager.setOnClickListener {
//                if (shopStatus?.templateId ?: 0 <= 0 && shopStatus?.haveCategory == false) {
//                    ToastUtils.showLong("请先完善店铺管理设置与分类设置，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                } else if (shopStatus?.templateId ?: 0 <= 0) {
//                    ToastUtils.showLong("请先完善店铺管理设置，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                } else if (shopStatus?.haveCategory == false) {
//                    ToastUtils.showLong("请先完善分类设置，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                } else if (loginInfo?.have_opentime == false) {
//                    ToastUtils.showLong("请先设置营业时间，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                } else if (loginInfo?.have_shoplogo == false) {
//                    ToastUtils.showLong("请先设置店铺logo，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                } else if (loginInfo?.have_mobile == false) {
//                    ToastUtils.showLong("请先设置联系电话，否则店铺不能进行正常营业与商品上传")
//                    return@setOnClickListener
//                }
//                GoodsListActivity.openActivity(requireContext())
//            }
//            // 商品分类
//            tvCategoryManager.setOnClickListener {
//                GoodsCategoryActivity.openActivity(requireContext())
//            }
//            // 菜单管理
//            tvMenuManager.setOnClickListener {
//                ActivityUtils.startActivity(MenuGoodsManagerActivity::class.java)
////             ActivityUtils.startActivity(GoodsPublishActivity::class.java)
////             GoodsPublishActivity.openActivity(context!!, "");
//            }
//            tvPopularize.setOnClickListener {
//                ActivityUtils.startActivity(PopularizeActivity::class.java)
//            }
//            // 营销设置
//            tvSaleSetting.setOnClickListener {
//                ActivityUtils.startActivity(SalesMarketingActivity::class.java)
//            }
//            // 钱包账户
//            tvWalletAccount.setOnClickListener {
//                ActivityUtils.startActivity(MyWalletActivity::class.java)
//            }
//            // 用户管理
//            tvUserManager.setOnClickListener {
//                UserManagerActivity.allUser(requireContext())
//            }
//            // 数据统计
//            tvDataAnalysis.setOnClickListener {
//                ActivityUtils.startActivity(StatsActivity::class.java)
//            }
//            // 库存预警
//            tvComeSoon.setOnClickListener {
//                ActivityUtils.startActivity(SalesActivityGoodsWarning::class.java)
//            }
//
//            // 今日数据
//            // 订单数量
//            storeDataOfTodayTv.singleClick {
//                model.setTime(startTime, endTime, 5)
//                EventBus.getDefault().post(TabChangeEvent(4))
//            }
//            // 销售额
//            salesDataOfTodayTv.singleClick {
//                //ActivityUtils.startActivity(StatsActivity::class.java)
//            }
//            // 用户数据
//            userDataOfTodayTv.singleClick {
//                UserManagerActivity.newUser(requireContext())
//            }
//
//
//            // 未接订单
//            llTodayUnTakeOrderCount.setOnClickListener {
//                EventBus.getDefault().post(TabChangeEvent(0))
//            }
//            // 已接订单
//            llMainWaitTakeGoods.setOnClickListener {
//                //待配送，即备货中
//                EventBus.getDefault().post(TabChangeEvent(1, "ACCEPT"))
//            }
//            // 配送中
//            llMainWaitSendGoods.setOnClickListener {
//                EventBus.getDefault().post(TabChangeEvent(1, "SHIPPED"))
//            }
//            // 待退款
//            llMainWaitRefund.setOnClickListener {
//                EventBus.getDefault().post(TabChangeEvent(2))
//            }
//            // 已完成
//            layoutTodayFinish.setOnClickListener {
//                //修改ViewModel中的时间
//                model.setTime(startTime, endTime, 3)
//                EventBus.getDefault().post(TabChangeEvent(3))
//            }
//            // 失效
//            layoutTodayInvalid.setOnClickListener {
//                model.setTime(startTime, endTime, 4)
//                EventBus.getDefault()
//                    .post(TabChangeEvent(4))
//            }
//            tvHelpDoc.setOnClickListener {
//                ActivityUtils.startActivity(HelpDocActivity::class.java)
//            }
//            //扫码上架
//            tvScan.setOnClickListener {
//                ActivityUtils.startActivity(GoodsScanActivity::class.java)
//            }
//        }
    }


}